/* eslint-disable no-unused-vars */
import {
  PageContainer,
  ProCard,
  ProForm,
  ProFormCheckbox,
  ProTable,
  BetaSchemaForm,
} from "@ant-design/pro-components";
import { Button, Modal, FloatButton } from "antd";
import React, { useMemo, useState, useRef } from "react";
import { useModel,history } from "umi";
import { Checkbox, Segmented } from "antd";
import {
  EditFilled,
  EyeFilled,
  EyeInvisibleFilled,
  MenuOutlined,
} from "@ant-design/icons";
import { Tooltip } from "antd";
import Visible from "@/components/Visible";
import EditorItem from "@/components/EditorItem";
import Limit from "@/components/Limit";
import IconFont from "@/components/IconFont";
import AutoTable from "@/components/AutoTable";
import ColumnSet from "@/components/ColumnSet/index";
import { Divider } from "antd";


const config = {
  add: {
    text: "新增",
  },
  import: {
    text: "导入",
  },
  export: {
    text: "导出",
  },
};

function updateNodeByPath(data, pathToUpdate, updatedNodeInfo) {
  return data.map((item) => {
    if (item.path === pathToUpdate) {
      return { ...item, ...updatedNodeInfo };
    } else if (item.routes) {
      return {
        ...item,
        routes: updateNodeByPath(item.routes, pathToUpdate, updatedNodeInfo),
      };
    }
    return item;
  });
}

function Pages({ routedata, eidtpage }) {
  const {
    initialState: { routerData, extralayout, preview },
    setInitialState,
  } = useModel("@@initialState");

  const formRef = useRef();

  const [modal, setModal] = useState({
    open: false,
    footer: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  const actions = useMemo(() => {
    return (
      routedata?.actions?.map((it) => {
        return (
          <Button
            key={it}
            onClick={() => {
              setModal((s) => ({
                ...s,
                open: true,
                title: "新增",
              }));
            }}
          >
            {config[it]?.text}
          </Button>
        );
      }) ?? []
    );
  }, [routedata?.actions]);

  return (
    <PageContainer
      token={{
        paddingInlinePageContainerContent: 20,
      }}
      extra={[
        ...actions,
        <Visible>
          <Button
            key="1"
            type="dashed"
            onClick={() => {
              setModal((s) => ({
                ...s,
                open: true,
                title: "编辑页面",
              }));
              setTimeout(() => {
                formRef?.current?.setFieldsValue({
                  ...routedata,
                });
              }, 10);
            }}
          >
            编辑
          </Button>
        </Visible>,
      ]}
      subTitle={
        <Button
          type="dashed"
          size="small"
          onClick={() => {
            setModal((s) => ({
              ...s,
              open: true,
              title: "字段设置",
            }));
          }}
        >
          字段设置
        </Button>
      }
    >
      <Modal {...modal} width={1200} destroyOnClose>
        {modal.title === "字段设置" && (
          <ColumnSet
            columns={routedata.columns ?? []}
            changeColumns={(value) => {
              setInitialState((s) => {
                const updateData = updateNodeByPath(
                  s.routerData,
                  routedata.path,
                  {
                    ...routedata,
                    columns: value,
                  }
                );
                return {
                  ...s,
                  routerData: updateData,
                };
              });
            }}
          ></ColumnSet>
        )}

        {modal.title === "编辑页面" && (
          <div
            style={{
              margin: "12px 0",
              gap: 12,
              display: "flex",
              flexDirection: "column",
              alignItems: "flex-start",
            }}
          >
            <div className="ltitle0">页面操作</div>
            <Checkbox.Group
              options={Object.entries(config)?.map(([key, value]) => {
                return {
                  label: value.text,
                  value: key,
                };
              })}
              defaultValue={routedata?.actions}
              onChange={(value) => {
                setInitialState((s) => {
                  const updateData = updateNodeByPath(
                    s.routerData,
                    routedata.path,
                    {
                      ...routedata,
                      actions: value,
                    }
                  );
                  return {
                    ...s,
                    routerData: updateData,
                  };
                });
              }}
            ></Checkbox.Group>
            <div className="ltitle0">页面风格</div>
            <Segmented
              options={[
                {
                  label: (
                    <div
                      style={{
                        padding: 4,
                        width: 120,
                      }}
                    >
                      <IconFont type="icon-table" />
                      <div>表格</div>
                    </div>
                  ),
                  value: "table",
                },
                {
                  label: (
                    <div
                      style={{
                        padding: 4,
                        width: 120,
                      }}
                    >
                      <IconFont type="icon-tab" />
                      <div>多Tab表格</div>
                    </div>
                  ),
                  value: "tab-table",
                },
                {
                  label: (
                    <div
                      style={{
                        padding: 4,
                        width: 120,
                      }}
                    >
                      <IconFont type="icon-tree-table" />
                      <div>左侧树+表格</div>
                    </div>
                  ),
                  value: "tree-table",
                },
              ]}
              onChange={(value) => {
                setInitialState((s) => {
                  const updateData = updateNodeByPath(
                    s.routerData,
                    routedata.path,
                    {
                      ...routedata,
                      component: {
                        ...(routedata.component ?? {}),
                        type: value,
                      },
                    }
                  );
                  return {
                    ...s,
                    routerData: updateData,
                  };
                });
              }}
            ></Segmented>
            <div className="ltitle0">页面说明</div>
            <ProForm
              formRef={formRef}
              submitter={false}
              onValuesChange={(value) => {
                setInitialState((s) => {
                  const updateData = updateNodeByPath(
                    s.routerData,
                    routedata.path,
                    {
                      ...routedata,
                      ...value,
                    }
                  );
                  return {
                    ...s,
                    routerData: updateData,
                  };
                });
              }}
            >
              <ProForm.Item
                transform={(value) => {
                  return {
                    remark: value ? value?.toHTML?.() : null,
                  };
                }}
                name={"remark"}
              >
                <EditorItem />
              </ProForm.Item>
            </ProForm>
          </div>
        )}

        {modal.title === "新增" && (
          <>
            <Button
              onClick={() => {
                history.push("/editor");
              }}
            >
              编辑表单
            </Button>
            {routedata?.addcolumns && (
              <>
                <Divider></Divider>
                <BetaSchemaForm
                  columns={routedata?.addcolumns ?? []}
                ></BetaSchemaForm>
              </>
            )}
          </>
        )}
      </Modal>

      <ProCard>
        <ProTable
          columns={routedata.columns ?? []}
          dataSource={[]}
          search={{
            filterType: "light", //轻量模式
            placement: "bottomLeft",
          }}
        ></ProTable>
        <FloatButton.Group
          trigger="click"
          type="primary"
          style={{
            right: 24,
          }}
          icon={<MenuOutlined />}
        >
          <Tooltip placement="left" title={preview ? "编辑" : "预览"}>
            <FloatButton
              icon={preview ? <EditFilled /> : <EyeFilled />}
              onClick={() => {
                setInitialState((s) => ({
                  ...s,
                  preview: !s.preview,
                }));
              }}
            />
          </Tooltip>
          <Visible>
            <Tooltip placement="left" title="编辑页面">
              <FloatButton
                onClick={() => {
                  eidtpage?.();
                }}
              />
            </Tooltip>
          </Visible>
        </FloatButton.Group>
      </ProCard>
      <div
        style={{
          backgroundColor: "#ffffff",
          marginTop: 24,
          borderRadius: 12,
          padding: 12,
        }}
      >
        <p>页面说明：</p>
        <Limit content={routedata?.remark}></Limit>
      </div>
    </PageContainer>
  );
}

export default Pages;
